<template>
  <div class="purchase-history">
    <r-header />
    <div class="page">
      <div class="header">
        <h1>购买记录</h1>
        <p>查看您的所有购买记录</p>
      </div>
      
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在加载购买记录...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="error" class="error">
        <p>{{ error }}</p>
        <button @click="loadPurchaseHistory" class="retry-btn">重试</button>
      </div>
      
      <!-- 购买记录列表 -->
      <div v-else-if="purchaseHistory.length > 0" class="history-list">
        <div class="history-item" v-for="item in purchaseHistory" :key="item.id">
          <div class="item-header">
            <div class="item-title">{{ item.productName }}</div>
            <div class="item-status" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </div>
          </div>
          
          <div class="item-content">
            <div class="item-info">
              <div class="info-row">
                <span class="label">订单号：</span>
                <span class="value">{{ item.orderNumber }}</span>
              </div>
              <div class="info-row">
                <span class="label">更新时间：</span>
                <span class="value">{{ formatDate(item.createdAt) }}</span>
              </div>
              <div class="info-row">
                <span class="label">支付金额：</span>
                <span class="value amount">¥{{ item.totalAmount }}</span>
              </div>
              <div class="info-row">
                <span class="label">支付方式：</span>
                <span class="value">{{ getPaymentMethodText(item.paymentMethod) }}</span>
              </div>
            </div>
            
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else class="empty">
        <div class="empty-icon">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" 
                  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h3>暂无购买记录</h3>
        <p>您还没有购买过任何套餐</p>
        <router-link to="/shop" class="btn btn-primary">去购买</router-link>
      </div>
    </div>
  </div>
</template>

<script type="text/javascript">
import { orderApi } from '@/api/product'

export default {
  name: "PurchaseHistory",
  data() {
    return {
      loading: false,
      error: null,
      purchaseHistory: [],
    }
  },
  methods: {
    // 加载购买记录
    async loadPurchaseHistory() {
      this.loading = true;
      this.error = null;
      
      try {
        // 获取当前用户ID（优先使用数据库ID，如果没有则使用手机号）
        const userId = this.$store.state.user.profile.id || this.$store.state.user.profile.phone_number;
        
        if (!userId) {
          this.error = '用户信息不完整，请重新登录';
          this.loading = false;
          return;
        }
        
        console.log('获取用户订单列表，用户ID:', userId);
        const response = await orderApi.getUserOrders(userId);
        
        if (response.success) {
          console.log('订单列表数据:', response.data);
          const orders = response.data || [];
          
          if (orders.length === 0) {
            this.purchaseHistory = [];
          } else {
            this.purchaseHistory = this.formatOrderData(orders);
          }
        } else {
          this.error = response.message || '获取购买记录失败';
        }
      } catch (error) {
        console.error('获取购买记录失败:', error);
        this.error = '网络错误，请检查网络连接后重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 格式化订单数据
    formatOrderData(orders) {
      return orders.map(order => {
        // 调试订单数据
        console.log('订单数据同步:', {
          id: order.id,
          status: order.status,
          createdAt: order.createdAt,
          updatedAt: order.updatedAt,
          paidAt: order.paidAt
        });
        
        return {
          id: order.id,
          orderNumber: order.orderNumber,
          productName: this.getProductNameFromOrder(order),
          status: order.status, // 直接同步status
          totalAmount: order.totalAmount,
          paymentMethod: order.paymentMethod,
          // 使用updatedAt作为订单时间，如果没有则使用createdAt
          createdAt: order.updatedAt || order.createdAt,
          paidAt: order.paidAt
        };
      });
    },
    
    // 从订单中获取商品名称
    getProductNameFromOrder(order) {
      // 根据权益信息推断商品类型
      if (order.totalChatCount === -1) {
        return 'VIP会员（无限制）';
      } else if (order.totalChatCount >= 500) {
        return '高级聊天套餐';
      } else if (order.totalChatCount >= 100) {
        return '基础聊天套餐';
      } else {
        return '体验套餐';
      }
    },
    
    
    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        'paid': 'status-paid',
        'pending': 'status-pending',
        'cancelled': 'status-cancelled',
        'refunded': 'status-refunded'
      };
      return statusMap[status] || 'status-unknown';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'paid': '已支付',
        'pending': '待支付',
        'cancelled': '已取消',
        'refunded': '已退款'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 获取支付方式文本
    getPaymentMethodText(method) {
      const methodMap = {
        'wechat': '微信支付',
        'alipay': '支付宝'
      };
      return methodMap[method] || '未知支付方式';
    },
    
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  },
  mounted() {
    this.loadPurchaseHistory();
  }
}
</script>

<style lang="scss" scoped>
.purchase-history {
  min-height: 100vh;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  padding-top: 80px; // 为固定导航栏留出空间
}

.page {
  padding: 2rem 1rem;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 3rem;
  
  h1 {
    font-size: 2.5rem;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 1rem;
  }
  
  p {
    font-size: 1.2rem;
    color: #9CA3AF;
  }
}

.overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.overview-card {
  background: rgba(31, 41, 55, 0.8);
  border-radius: 15px;
  padding: 2rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  gap: 1.5rem;
  
  .overview-icon {
    width: 60px;
    height: 60px;
    background: rgba(59, 130, 246, 0.1);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #3B82F6;
    
    svg {
      width: 30px;
      height: 30px;
    }
  }
  
  .overview-content {
    flex: 1;
    
    h3 {
      font-size: 1.1rem;
      color: #9CA3AF;
      margin-bottom: 0.5rem;
    }
    
    .overview-value {
      font-size: 2rem;
      font-weight: bold;
      color: #10B981;
      margin-bottom: 0.5rem;
    }
    
    .overview-desc {
      font-size: 0.9rem;
      color: #6B7280;
    }
  }
}

.loading, .error, .empty {
  text-align: center;
  padding: 4rem 2rem;
  color: #ffffff;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #374151;
  border-top: 4px solid #3B82F6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-btn {
  background: #3B82F6;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  margin-top: 1rem;
  
  &:hover {
    background: #2563EB;
  }
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.history-item {
  background: rgba(31, 41, 55, 0.8);
  border-radius: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    
    .item-title {
      font-size: 1.3rem;
      font-weight: bold;
      color: #ffffff;
    }
    
    .item-status {
      padding: 0.5rem 1rem;
      border-radius: 20px;
      font-size: 0.9rem;
      font-weight: 600;
      
      &.status-paid {
        background: rgba(16, 185, 129, 0.1);
        color: #10B981;
      }
      
      &.status-pending {
        background: rgba(245, 158, 11, 0.1);
        color: #F59E0B;
      }
      
      &.status-cancelled {
        background: rgba(239, 68, 68, 0.1);
        color: #EF4444;
      }
      
      &.status-refunded {
        background: rgba(107, 114, 128, 0.1);
        color: #6B7280;
      }
    }
  }
  
  .item-content {
    padding: 1.5rem;
  }
  
  .item-info {
    margin-bottom: 1.5rem;
  }
  
  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      color: #9CA3AF;
      font-size: 0.95rem;
    }
    
    .value {
      color: #ffffff;
      font-weight: 600;
      
      &.amount {
        color: #10B981;
        font-size: 1.1rem;
      }
    }
  }
  
}

.empty {
  .empty-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto 2rem;
    background: rgba(107, 114, 128, 0.1);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #6B7280;
    
    svg {
      width: 40px;
      height: 40px;
    }
  }
  
  h3 {
    font-size: 1.5rem;
    color: #ffffff;
    margin-bottom: 1rem;
  }
  
  p {
    color: #9CA3AF;
    margin-bottom: 2rem;
  }
  
  .btn {
    padding: 1rem 2rem;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 600;
    font-size: 1rem;
    transition: all 0.3s ease;
    
    &.btn-primary {
      background: linear-gradient(135deg, #3B82F6, #1D4ED8);
      color: white;
      
      &:hover {
        background: linear-gradient(135deg, #2563EB, #1E40AF);
        transform: translateY(-2px);
        box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
      }
    }
  }
}

@media (max-width: 768px) {
  .page {
    padding: 1rem;
  }
  
  .header h1 {
    font-size: 2rem;
  }
  
  .overview {
    grid-template-columns: 1fr;
  }
  
  .overview-card {
    flex-direction: column;
    text-align: center;
  }
  
  .benefits-info {
    grid-template-columns: 1fr;
  }
}
</style>
